package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redisson;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping({"/", "index", "/index.html"})
    public String indexPage(Model model) {
        // 获取一级分类所有缓存
        List<CategoryEntity> catagories = categoryService.getLevel1Categorys();
        model.addAttribute("categorys", catagories);
        return "index";
    }

    @ResponseBody
    @RequestMapping("index/json/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatlogJson() {

        Map<String, List<Catelog2Vo>> map = categoryService.getCatelogJson();
        return map;
    }


    @ResponseBody
    @RequestMapping("string")
    public String returnString() {
        // 获取一把锁，只要锁名字一样，就是同一把锁
        RLock lock = redisson.getLock("my-lock");

        // 加锁
//        lock.lock();//默认加锁时间为30s
        //1. 锁的自动续期，如果业务超长，运行期间自动续上新的30s
        //2. 加锁的业务只要完成，就不会给当前锁续期，即使不手动解锁，锁也默认在30s以后删除

        //lock.lock(10, TimeUnit.SECONDS); // 10s后自动解锁，自动解锁时间一定要大于业务的执行时间，因为时间到了以后不会自动续期
        //1. 如果我们传递了锁的超时时间，就发送给redis执行脚本，进行占锁，默认超时时间时我们的指定时间
        //2. 如果我们为指定锁的超时就是用30*1000看门狗的默认时间
        //  只要占锁成功就会启动一个定时认为每过【最大时间/3】会刷新时间

        //一般使用lock.lock(30, TimeUnit.SECONDS);
        lock.lock(10, TimeUnit.SECONDS);

        try {
            System.out.println("上锁"+Thread.currentThread().getId());
            System.out.println("执行业务代码");
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("解锁"+Thread.currentThread().getId());
            lock.unlock();
        }

        return "hello";
    }


    //保证一定能读到最新数据，修改期间，写锁是一个排他锁（互斥锁，独享锁），读锁是一个共享锁
    //写锁没释放读就必须等待
    //读+读：相当于无锁，只会在redis钟记录好，所有当前的读锁。他们都会同时加锁成功
    //写+读：等待写锁释放
    //写+写：阻塞方式
    //读+写：有读锁。也需要等待
    //只要有写的存在，都必须等待
    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {
        String s = "";
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.writeLock();
        rLock.lock(10,TimeUnit.SECONDS);
        try {

            s = UUID.randomUUID().toString();
            stringRedisTemplate.opsForValue().set("key",s);
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }
        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue() {
        String s = "";
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.readLock();
        rLock.lock();
        try {
            s = stringRedisTemplate.opsForValue().get("key");
        }finally {
            rLock.unlock();
        }
        return s;
    }

    @GetMapping("/door")
    @ResponseBody
    public String door() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();
        return "解锁";
    }

    @GetMapping("/gogogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable("id") Integer id) throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();
        return id.toString();
    }

    @GetMapping("/park")
    @ResponseBody
    public String park() {
        RSemaphore pack = redisson.getSemaphore("pack");
        try {
            pack.acquire(2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "停车2个";
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() {
        RSemaphore pack = redisson.getSemaphore("pack");
        try {
            pack.release(2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "开走2个";
    }

}
